package se.webbzon.boltzmann.game.event.predefined;

import java.util.HashMap;
import java.util.Map;

import se.webbzon.boltzmann.game.event.AbstractGameEvent;
import se.webbzon.boltzmann.game.event.AbstractTargetEvent;
import se.webbzon.boltzmann.game.event.GameEventListener;
import se.webbzon.boltzmann.game.sequence.Sequence;
import se.webbzon.oschi01.worldarea.WorldArea;
import se.webbzon.oschi01.worldobject.WorldObject;

public class PredefinedEvent extends AbstractTargetEvent {
	
	// The binding of this predefined event
	private final WorldObject binding;
	
	// A factory of all the available predefined events
	private final Map<String,PredefinedEventFactory> factories;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public PredefinedEvent(Sequence sequence, WorldObject binding, String[] arguments) {
		super(sequence, arguments);
		this.binding = binding;
		factories = new HashMap<String,PredefinedEventFactory>();
		factories.put("intro", new PEIntro());
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	@Override protected void onBegin(WorldArea world) {
		AbstractGameEvent event;
		event = createEvent(getArgument(0));
		if (event != null) {
			event.addListener(new GameEventListenerImpl());
			event.begin(world);
		} else
			end();
	}

	@Override protected void onEnd() {};
	
	/*============================================================
	Private Methods
	============================================================*/
	
	/** Creates a new predefined game event with the given name. **/
	private AbstractGameEvent createEvent(String name) {
		PredefinedEventFactory factory = factories.get(name.toLowerCase());
		if (factory == null)
			return null;
		else {
			return factory.createEvent(getSequence(),binding,getArgument(1));
		}
	}
	
	/*============================================================
	Private Classes
	============================================================*/
	
	/** An implementation of a game event listener. **/
	private final class GameEventListenerImpl implements GameEventListener {

		@Override public void onBegin(AbstractGameEvent event) {};

		@Override public void onEnd(AbstractGameEvent event) {
			end();
		}
		
	}

}
